<template>
  <div class="adventures">
    <div class="adventuresBox">
      <div class="adventuresTop">
        <div class="adventuresMain">
          <div class="adventParse">
            <div class="adventLotLogin">
              <img src="../../../assets/images/theColor/adventures/lotteryLogo.png" alt="">
            </div>
            <div class="adventDate">
              <section>
                当前开奖 <span>{{prevDate}} </span>期
              </section>
              <section>
                <div class="adventDraw" :class="{'red': _Format.lotColor(currentLotteryData[0], $route.query.code) === 'red', 'black': _Format.lotColor(currentLotteryData[0], $route.query.code) === 'black'}">
                  <p class="adventP" v-for="current in currentLotteryData"><span>{{current}}</span></p>
                </div>
              </section>
            </div>
            <router-link :to="{name:'theResults',query:{code:$route.query.code,name:lotteryName}}" class="adventList" tag="div">
              <section>历史开奖 <span>{{startNum.slice(-4)}}-{{endNum.slice(-4)}} </span>期</section>
              <section>
                <p v-for="(hisItem,hisIndex) in historyData" v-if="hisIndex<5" :class="{'red': _Format.lotColor(hisItem.data[0], $route.query.code) === 'red', 'black': _Format.lotColor(hisItem.data[0], $route.query.code) === 'black'}"><span>{{hisItem.data[0]}}</span></p>
              </section>
            </router-link>
          </div>
        </div>
      </div>
      <div class="adventGamble divFlex">
        <div class="adventGambleLeft">
          <img src="../../../assets/images/theColor/adventures/bigZP.png" alt="">
          <router-link :to="{name:'colorRules',query:{code:$route.query.code}}" tag="div" class="rulesBox">游戏规则</router-link>
          <!--倒計時-->
          <div class="countTimed">
            <p><span>{{date}}</span>期 倒计时</p>
            <p class="count"><span>{{countDownStr}}</span></p>
          </div>
        </div>
        <div class="adventGambleRight">
          <!---->
          <div class="adventNumberT" v-for="(group,groupIndex) in groupLotData"
               :class="{'groupForm': groupIndex === 1, 'classGro': groupIndex === 2, 'touchOffCls': groupIndex === 3}">
            <ul class="number">
              <li v-for="(dat,dataIndex) in group.playList[0].dataList" class="boxSizing">
                <article class="dataArticle"
                         :class="{'groupDataFirst': groupIndex === 0,'groupDataForm': groupIndex === 1, 'clsArticle': groupIndex === 2, 'touchDataOffCls': groupIndex === 3}"
                         @click="numerical($event, dat, dataIndex, group, partCls[groupIndex])" @contextmenu="colorMouseDown($event,dat,group)">
                  <section :class="{'dataBlack': _Format.lotColor(dat.name || '0', $route.query.code) === 'black'}"><span>{{dat.name}}</span>
                  </section>
                  <div class="chipDiv chip" v-if="dat.status">
                    <img src="../../../assets/images/theColor/adventures/k.png" alt="" class="amountDesk">
                  </div>
                </article>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <!--筹码-->
      <div class="jettonAmount">
        <div class="betChipsBox">
          <div class="betChips">
            <div class="betMoney"><p>下注金额：<span>{{totalAmount}}元</span></p></div>
            <div class="chipItem relative" :class="{chipOn:chipIndex==chipCurIndex}"
                 v-for="(chipItem,chipIndex) in chipVal" @click="chipSelectEvent(chipIndex,chipItem)">
              <img :src="_Modulation.getChipImg(chipItem)" alt="">
            </div>
            <div class="betMoney accountMoney relative">
              <div class="chipItem relative" :class="{chipOn:isAllIn}">
                <img :src="_Modulation.getChipImg('allIn')" alt="">
              </div>
              <p>账户余额：<span>{{accountMoney}}元</span></p>
            </div>
          </div>
          <div class="funBtnBox">
            <div class="funBtnItem relative clearAll" @click="empty"><p class="absmiddle">清桌</p></div>
            <div class="funBtnItem relative confirm" @click="confirm"><p class="absmiddle">确认投注</p></div>
            <div class="funBtnItem relative allIn" :class="{on:isAllIn}" @click="allInEvent"><p class="absmiddle">梭哈</p></div>
          </div>
        </div>
      </div>
    </div>

    <div class="betRecordHis newLotteryW">
      <newBetRecord ref="betRecord"></newBetRecord>
    </div>
    <setABet v-if="setABetTrue"></setABet>
  </div>
</template>

<script>
  import "./main.scss";
  import setABet from '../../theColor/color/transfer/setABet/index';
  import newBetRecord from '../newBetRecord/index';
  import {mapState} from 'vuex';
  export default {
    data() {
      return {
        lotteryCode: "", // 当前code
        lotteryName: "", // 彩种名称
        prevDate: "", // 上一期的期号
        date: "", // 本期期号
        countDownStr: "00:00:00", // 时间
        countDown: 60, // 倒计时
        stopCountDown: 30, // 去除封盘时间
        stopBet: false, // false 否 true 是
        stopStatus: false, // 是否停售
        setTimer: "",
        interValObj: "",
        adventuresList: [], //投注号码
        playData: [], // 数据
        BettingData: [], // 当前投注数据
        currentLotteryData: [], // 开奖结果
//        balanceAmount: 0, // 余额
        totalAmount: 0, // 总金额
        accountMoney: 0, // 账户余额
        accountMoneyCopy: 0, // 账户余额
        groupLotData: [], //group 数据
        historyData: [], // 历史数据
        startNum: '',//历史开奖期号
        endNum: '',//历史开奖期号
        chipVal: [1, 5, 10, 50, 100, 1000, 10000],//筹码
        chipCurIndex: 2,//选中筹码下标
        currentChip: 10,//选中筹码
        partCls: [".groupDataFirst", ".groupDataForm", ".clsArticle", ".touchDataOffCls"], // cls
        setABetTrue: false,
        holdBack: false,
        isAllIn: false,//是否梭哈
      }
    },
    computed: {
      ...mapState({
        recordColorData: state => state.mutations.recordColorData,
        userInfo: state => state.mutations.userInformation,
      }),
    },
    activated() {
      this.init();
    },
    deactivated() {
      let that = this;
      window.clearInterval(that.interValObj);
      window.clearInterval(that.setTimer);
      that.empty();
      that.stopStatus = false;
    },
    methods: {
      init(){
        this.clearData();
        this.initData();
        this.activation();
//        if(this.holdBack) return;
        this.getlotteryInfo();
      },
      initData(){
        this.$refs.betRecord.getMyBetRecData();
        let that = this,
          index = parseInt(that.$route.query.code);
        let data = that.recordColorData[index].data;
        if (that.recordColorData[index].data.length <= 0) return;
        that.stopStatus = data.status == '1' ? false : true;
        if (!data.code) return;
        that.data = data.nowNumber || '';
        that.lotteryName = data.name || '';
        that.prevDate = data.number || '';
        that.playGroupName = data.groupList[0].name || '';
        that.historyData = data.dataLit || [];
        that.accountMoneyCopy = that.userInfo.memberInfo.amount;
        if(that.historyData.length>5){
          that.startNum = that.historyData[0].number;
          that.endNum = that.historyData[4].number;
        }else if(that.historyData.length>0){
          that.startNum = that.historyData[0].number;
          that.endNum = that.historyData[that.historyData.length-1].number;
        }
        that.empty();
      },
      clearData() {
        this.chipCurIndex = 2;
        this.currentChip = 10;
        this.setABetTrue = false;
        this.data = '';
        this.prevDate = '';
      },
      //监听浏览器当前页面是否被激活的事件
      activation() {
        let that = this;
        let reLoadLeftTime = false;
        //监听浏览器当前页面是否被激活的事件
        let hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' : null;
        let visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
        let onVisibilityChange = function () {
          if (!document[hiddenProperty]) {
            reLoadLeftTime = true;
            window.cancelAnimFrame = (function(){
              return  window.cancelAnimationFrame       ||
                window.webkitCancelAnimationFrame ||
                window.mozCancelAnimationFrame   ||
                function(id){
                  clearTimeout(id);
                };
            })();
            that.getlotteryInfo();
          }
        };
        document.addEventListener(visibilityChangeEvent, onVisibilityChange);

        that.$router.beforeEach((route, redirect, next) => {
          document.removeEventListener(visibilityChangeEvent, onVisibilityChange);
          next();
        });
      },
      // 获取数据
      getlotteryInfo() {
        let that = this;
        // 投注数据请求
        that.lotteryCode = that.$route.query.code || '2002';
        that._Util.post(that, that._Api.POST_CREDIT_LOTTERY_DATA, {lotteryCode: that.lotteryCode}, (data) => {
          that.holdBack = true;
          that.accountMoney = data.amount || '0';
          that.accountMoneyCopy = data.amount || '0';
          // 数据处理
          data.groupList.forEach((v,g) => {
            v.playList[0].dataList.forEach((p) => {
              p.amount = 0;
              p.status = false;
            });
          });
          // 两面组合
          let dataListSide = ["","","","","",""];
          let U = 0;
          data.groupList[3].playList[0].dataList.forEach((d)=> {
            switch(parseInt(d.id)) {
              case 4148:
                U = 0;
                break;
              case 4158:
                U = 1;
                break;
              case 4156:
                U = 2;
                break;
              case 4157:
                U = 3;
                break;
              case 4159:
                U = 4;
                break;
              case 4149:
                U = 5;
                break;
            }
            dataListSide.splice(U,1,d);
          });
          data.groupList[3].playList[0].dataList = dataListSide;
          // 获取数据
          that.playData = data;
          that.lotteryName = that.playData.name;
          // 获取投注数据
          that.groupLotData = that.playData.groupList;
          // 获取余额
//          that.balanceAmount = data.amount;
          // 上一期的期号与本期期号
          that.prevDate = that.playData.number;
          that.date = that.playData.nowNumber;
          // 获取倒计时
          that.countDown = that.playData.countDown || '';
          that.stopCountDown = that.playData.stopCountDown || 0;
          that.stopStatus = that.playData.status == '1' ? false : true;
          // 获取开奖结果
          that.currentLotteryData = data.data || [];
          // 历史数据
          that.historyData = that.playData.dataLit || [];
          that.$store.commit('HIS_REW_DATA', that.historyData);
          if(that.historyData.length>5){
            that.startNum = that.historyData[0].number;
            that.endNum = that.historyData[4].number;
          }else if(that.historyData.length>0){
            that.startNum = that.historyData[0].number;
            that.endNum = that.historyData[that.historyData.length-1].number;
          }
          if (!that.stopStatus) {
            that.startCountDown();
            that.upDateLastData();
          }
          let lotteryData = {
            id: parseInt(that.$route.query.code),
            data: data
          };
          that.$store.commit('RECORD_COLOR_DATA', lotteryData);
        });
      },
      // 更新最新一期的期号和开奖结果
      upDateLastData() {
        let that = this;
        that.setTimer = setInterval(() => {
          if (parseInt(that.date) - parseInt(that.prevDate) === 1|| !that.$route.query.code) {
            clearInterval(that.setTimer);
          } else {
            let submitData = {
              lotteryCode: that.$route.query.code
            };
            if (!that.stopStatus&& (that.$route.name === "adventures")) {
              that._Util.post(that, that._Api.POST_LOTTERY_DATA_LAST, submitData, (data) => {
                // 更新期号
                that.prevDate = data.openDataList[0].number;
                that.date = data.nextNumber || '';
//                that.countDown = data.countDown || -1;
//                that.stopCountDown = data.stopCountDown;
                // 更新开奖号码
                if(parseInt(that.date) - parseInt(that.prevDate) === 1) {
                  that.currentLotteryData = data.openDataList[0].data;;
                }
                //获取开奖历史数
                if (that.prevDate > that.historyData[0].number) {
                  that.historyData.unshift(data.openDataList[0]) || [];
                  that.historyData = that.historyData.slice(0, 10);
                  that.$store.commit('HIS_REW_DATA', that.historyData);
                }
                if(that.historyData.length>5){
                  that.startNum = that.historyData[0].number;
                  that.endNum = that.historyData[4].number;
                }else if(that.historyData.length>0){
                  that.startNum = that.historyData[0].number;
                  that.endNum = that.historyData[that.historyData.length-1].number;
                }
              }, (data) => {
                clearInterval(that.setTimer);
              },'', true);
            } else {
              clearInterval(that.setTimer);
            }
          }
        }, 6000);
      },
      //筹码选中事件
      chipSelectEvent(index, val) {
        this.chipCurIndex = index;
        this.currentChip = val;
        this.isAllIn = false;
      },
      // 选号触发
      numerical(e, baccard, index, group, cls) {
        let that = this;
        if(that.accountMoney<=0){
          that._Util.showAlert('余额不足');
          return;
        }
        if (that.accountMoney < that.currentChip) {
          that._Util.showAlert('余额不足');
          return;
        }
        if (!baccard.status) {
          baccard.status = true;
        }
        let selectChip = that.currentChip;
        baccard.amount += parseFloat(selectChip);
        // 金币效果
        let chipAmount = $(cls).eq(index);
        setTimeout(() => {
          that._Util.parabola(e, baccard, chipAmount,'','',that.isAllIn);
        }, 50);
        that.retentionInputData(baccard, group);
      },
      //右击事件
      colorMouseDown(e, baccard, group) {
        let that = this;
        baccard.status = false;
        console.log("ddd",baccard);
        if (e.which == 3) {
          baccard.amount = 0;
//          var amount = baccard.amount;
//          $(clsObj).eq(listIndex).find('.credAmountDiv').eq(dataIndex).removeClass('credAmountAnimation').text(amount);
          that.retentionInputData(baccard, group);
          e.preventDefault();
        }
      },
      // 倒计时
      startCountDown() {
        let that = this;
        that.stopBet = false;
        if (that.stopCountDown < 0) {
          that.stopBet = true;
          that.$store.commit('ROTARY', that.stopBet);
        }
        if (!that.stopStatus && that.countDown > 0) {
          window.clearInterval(that.interValObj);
          that.interValObj = window.setInterval(
            function () {
              that.countDownSecond();
            }.bind(this), 1000);
        }
      },
      countDownSecond() {
        let that = this;
        if (that.$route.name === that._Format.gameName(that.$route.query.code)) {
          if (that.countDown > 0) {
            that.countDown -= 1;
            if (that.stopCountDown > 0) {
              that.stopCountDown -= 1;
            } else {
              if (that.stopCountDown === 0) {
                that._Util.showAlert(that, "已封盘");
                that.stopBet = true;
                that.$store.commit('BOTTOM_POUR_DATA', that.stopBet);
              }
              that.stopCountDown -= 1;
            }
            that.countDownStr = that._Util.formatTime(that.stopCountDown, that.countDown, that.stopBet);
          } else if (that.countDown === 0) {
            // 清空回调方法
            that._Util.showAlert(that, "新的一期已经开始");
            that.stopBet = false;
            that.countDown = "";
            that.stopCountDown = 0;
            that.getlotteryInfo();
            that.empty();
            that.$store.commit('BOTTOM_POUR_DATA', that.stopBet);
          }
        }
      },
      // 保留投注数据
      retentionInputData(list, group) {
        let that = this;
        let injectionData = {
          playedGroupCode: group.code || '',        //玩法组code
          playedGroupName: group.name||'',        //玩法组名称
          playedId: list.id,                          //玩法id
          playedName: list.name,                      //玩法名称
          actionNum: 1,                               //单个玩法注数
          actionData: list.name,                      //投注号码
          rebate: 0,                                  //返点
          rebateAmount: 0,
          amount: list.amount,                      //金额
          odds: list.odds,                          //赔率
          mode: 2,                                  //模式   1.官方   2信用
          multiple: 1
        };
        that.addInputData(injectionData);
      },
      // 添加投注数据
      addInputData(json) {
        let that = this;
        let len = that.BettingData.length;
        if (that.BettingData.length === 0) {
          if(json.amount>'0'){
            that.BettingData.push(json);
          }
        } else {
          that.BettingData.forEach((bet, i) => {
            bet.playedId = parseInt(bet.playedId);
            json.playedId = parseInt(json.playedId);
            if (bet.playedId === json.playedId) {
              if(json.amount>'0'){
                that.BettingData.splice(i, 1);
                that.BettingData.push(json);
              }else{
                that.BettingData.splice(i, 1);
              }
              return;
            } else if (i === len - 1) {
              if(json.amount>'0'){
                that.BettingData.push(json);
              }else{
                that.BettingData.splice(i, 1);
              }
            }
          });
        }
        that.totalCalVal();
        // that.$store.commit('INIT_LOTTERY_DATA', that.BettingData);
      },
      //计算总额
      totalCalVal() {
        let that = this,
          amountObj = that._Util.totalNumberNotes(that.BettingData);
        that.totalAmount = amountObj.amount;
        that.accountMoney = parseInt((that.accountMoneyCopy - that.totalAmount) * 100) / 100;
      },
      // 清空
      empty() {
        let that = this;
        // 清空状态
        that.groupLotData.forEach((v) => {
          v.status = false;
          v.amount = 0;
          v.playList.forEach((val) => {
            val.dataList.forEach((va) => {
              va.status = false;
              va.amount = 0;
            });
          });
        });
        // 清空总金额
        that.totalAmount = 0;
        that.accountMoney = that.accountMoneyCopy;
        that.isAllIn = false;
        this.chipCurIndex = 2;
        this.currentChip = 10;
        // 清空footer
//        that.$refs.footer.statusInit();
        // 清空保存数据
        that.BettingData = [];
      },
      //确认投注
      confirm() {
        let that = this;
        if (that.stopStatus) {
          that._Util.showAlert('暂停销售');
          return;
        }
        if (that.stopBet) {
          that._Util.showAlert('已封盘');
          return;
        }
        if (that.BettingData.length > 0) {
          let athectData = {
            number: that.date,
            name: that.lotteryName,
            data: that.BettingData
          };
          that.$store.commit('INIT_LOTTERY_DATA', athectData);
          that.setABetTrue = true;
        } else {
          that._Util.showAlert('你还没有投注记录');
        }
      },
      //梭哈点击事件
      allInEvent() {
        this.chipCurIndex = 7;
        this.isAllIn = true;
        this.currentChip = this.accountMoney;
      },
    },
    components: {
      setABet,
      newBetRecord
    }
  }
</script>
